'use strict';

import { merchant_wineModel } from "../model/merchant_wine";
import { merchantService } from "../service/merchant";
import { ServiceBase, Exceptions } from '../kalend';
import config from "../middleware/config";
import { usertokenService } from "./usertoken";
import { customer_accountService } from "./customer_account";
import { sms } from "../middleware/sms";
import { customer_orderwineService } from "./customer_orderwine";
import { merchantapplywineService } from "./MerchantApplyWine";
import _ = require("underscore");
import { winelistService } from "./winelist";
class Merchant_wineService extends ServiceBase {
    constructor() {
        super(merchant_wineModel)
    }

    async querypage(params: any) {
        const offset = params.offset || 1;
        const limit = params.limit || 15;
        const mid = params.mid;
        let data = await this.queryPagination(offset, limit, {
            filter: { merchantid: mid, status: 1 },
            populateOptions: {
                path: 'wineid',
                select: 'winename Aroma Alcohol price capacity img type  specs num status'
            },
            sort: 'order',
            select: 'wineid stock count status'
            // select: 'winename Aroma Alcohol price capacity img type',
            // sort: 'order'
        });
        data.rows = data.rows.filter((a) => {
            return a.wineid && a.wineid.status === 1;
        });
        data.rows = data.rows.map((a) => {
            for (const key in a.wineid) {
                if (a.wineid[key] && key != '_id' && key != 'status') {
                    a[key] = a.wineid[key];
                }
            }
            delete a.wineid;
            return a;
        });
        return data;
    }

    async queryall(params: any) {
        if (!params.token) {
            throw Exceptions.notoken();
        }
        let userid = (await usertokenService.getToken(params.token)).userid;
        let res: any = {};
        let wines = await this.queryAll({
            filter: { merchantid: params.mid, status: 1 },
            populateOptions: {
                path: 'wineid',
                select: 'winename Aroma Alcohol price capacity img type specs num status'
            },
            sort: 'order',
            select: 'wineid stock count status'
            //select: 'winename img count capacity Alcohol Aroma type stock price',
            //sort: 'order'
        });
        wines = wines.filter((a) => {
            return a.wineid && a.wineid.status === 1;
        });
        res.wines = wines.map((a) => {
            for (const key in a.wineid) {
                if (a.wineid[key] && key != '_id' && key != 'status') {
                    a[key] = a.wineid[key];
                }
            }
            delete a.wineid;
            return a;
        });
        let merchant = await merchantService.queryById(params.mid);
        let user = await customer_accountService.querySingle({ _id: userid }, { select: 'coinbalance mealbalance' });
        res.coinbalance = user.coinbalance;
        res.mealbalance = user.mealbalance;
        res.percapita = merchant.percapita;
        // 获取
        return res;
    }

    //根据商户id获取酒水
    async querybymerchantid(params: any) {
        let filter: any = {};
        if (params.mid) {
            filter.merchantid = params.mid;
        }
        let wines = await this.queryPagination(params.offset, params.limit, {
            filter: filter,
            populateOptions: {
                path: 'wineid',
                select: 'winename Aroma Alcohol price capacity img type specs num status'
            },
            sort: 'order',
            select: 'wineid stock count status'
        });
        wines.rows = wines.rows.filter((a) => {
            return a.wineid && a.wineid.status === 1;
        });
        wines.rows = wines.rows.map((a) => {
            for (const key in a.wineid) {
                if (a.wineid[key] && key != '_id' && key != 'status') {
                    if (key === 'winename' && a.wineid[key].length > 10) {
                        a[key] = a.wineid[key].substr(0, 10);
                    } else {
                        a[key] = a.wineid[key];
                    }
                }
            }
            delete a.wineid;
            var type = a.type;
            if (type) {
                if ((type as Array<any>).findIndex((b) => {
                    return b == 1;
                }) >= 0) {
                    a.typename = '酒';
                } else {
                    a.typename = '饮料';
                }
            }
            return a;
        })
        return wines;
    }

    //根据商户id获取酒水列表并计算可补货箱数
    async querybymerchantidcan(mid: any) {
        let filter: any = {
            status: 1,
            merchantid: mid
        };
        let winelists = await this.queryAll({
            filter: filter,
            populateOptions: {
                path: 'wineid',
                select: 'winename img specs status'
            },
            sort: 'order',
            select: 'wineid stock'
        });
        winelists = winelists.filter((a) => {
            return a.wineid && a.wineid.status === 1;
        });
        /** 获取消费酒水数 */
        let wineCostList = await customer_orderwineService.queryWineCostByMid(mid);
        /** 获取补货数 */
        let winelist = await merchantapplywineService.queryWineApplyByMid(mid);
        /** 申请补货数量 */
        let appcount = 0;
        winelists = winelists.map((a) => {
            for (const key in a.wineid) {
                if (a.wineid[key] && key != '_id' && key != 'status') {
                    a[key] = a.wineid[key];
                }
            }
            delete a.wineid;
            // 消费酒水数
            let winecostnum = 0;
            const wwc = wineCostList.find((wc) => {
                return wc._id && wc._id.toJSON() == a._id.toJSON();
            });
            if (wwc) {
                winecostnum = wwc.total;
            }
            // 已补库存数
            let appnum = 0;
            const ites = winelist.filter((wl) => {
                return wl.wineid === a._id.toJSON();
            });
            if (ites && ites.length > 0) {
                appnum = eval(_.pluck(ites, 'count').join('+'));
            }
            // 可补货数量
            a.cnum = winecostnum - appnum;
            // 可申请配送数量
            a.count = Math.floor(a.cnum / a.specs);
            a.maxapp = a.count;
            appcount += a.count * a.specs;
            return a;
        });
        return {
            items: winelists,
            appcount: appcount
        };
    }

    // 订单支付成功-更新商户酒水库存
    async updatewinestock(params: any) {
        let wines = await this.queryAll({ filter: { merchantid: params.mid, status: 1 } });
        if(wines){
            console.log('买单：开始更新酒水库存');
        let orderwines = params.wines;
        for (let i of orderwines) {
            if (i.count > 0) {
                let wineone = wines.find((wine) => {
                    return wine && wine._id && wine._id.toJSON() == i._id;
                })

                if (wineone) {
                    let scount = (wineone.stock || 0) - i.count;
                    this.update(i._id, { stock: scount });

                    // 库存低于20短信提醒商家
                    if (scount < 20) {
                        const mer = await merchantService.querySingle({ _id: params.mid }, {
                            populateOptions: {
                                path: 'legaluserid',
                                select: 'name phone'
                            },
                            select: 'name legaluserid'
                        });
                        if (mer.legaluserid && mer.legaluserid.phone) {
                            sms.sendmsg2(mer.legaluserid.name, mer.name, mer.legaluserid.phone, wineone.winename);
                        }
                    }
                }
            }
        }
        }
    }

    //品牌大使更新库存
    async agentupdatwinesstock(parms: any) {
        return this.update(parms._id, {
            stock: parms.stock
        });
    }

    async save(doc: any) {
        const apiurl = config.get("apiforarea")["imgurl"];
        if (doc.img) {
            if (doc.img.indexOf('http') < 0) {
                doc.img = apiurl + doc.img;
            }
        }
        if (doc._id) {
            return this.update(doc._id, doc);
        } else {
            return this.create(doc);
        }
    }

    async initWine(merchantid: any) {
        let items = await winelistService.queryalls();
        items = items.map((a) => {
            a.merchantid = merchantid;
            delete a.createTime;
            delete a.updateTime;
            a.wineid = a._id;
            delete a._id;
            a.stock = 0;
            a.count = 0;
            return a;
        });
        this.createMany(items);
    }

    async queralls(filter: any, select: any, sort: any) {
        return this.queryAll({
            filter: filter,
            select: select,
            sort: sort
        })
    }
    async getWines(wids: Array<any>) {
        let data = await merchant_wineModel.aggregate([
            {
                $match: {status: 1, _id: { $in: wids } }

            },
            {
                $lookup: {
                    from: "winelists",
                    localField: "wineid",
                    foreignField: "_id",
                    as: "winedata"
                }
            },
            {
                $unwind: "$winedata"
            },
            {
                $project: {
                    _id: '$_id',
                    merchantid: '$merchantid',
                    num: '$winedata.num',
                    price: '$winedata.price',
                    order: { '$divide': ['$winedata.price', '$winedata.num'] }
                    //order: { '$multiply': ['$winedata.price', '$winedata.num'] }
                }
            },
            {
                $sort: { order: -1 }
            }
        ]);
        return data;
    }
}

export const merchant_wineService = new Merchant_wineService();